''' 
Copyright 2013 Robert Edger

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
'''

import pickle
import requests
import sys
from snarl import showNotification
from snarl import registerSnarl
import types
from time import sleep
import redditConfig

def main():
    pickleFile = redditConfig.pickleFile

    #verify pickle exists, if not quit
    try:
        with open(pickleFile) as f: pass
    except IOError as e:
        print 'users file does not exist'
        sys.exit(0)

    #make sure we are registered with Snarl
    registerSnarl()

    #Unpickle the list of users
    #the list is really just a Map between a username and the last seen UTC of a post
    f=open(pickleFile,'rb')
    userList = pickle.load(f)
    f.close()

    #we only want to get the latest post
    params = {'limit':1}
    #used in debug to make sure the prog isn't failing
    didPost = False

    print 'starting traversal'

    #loop through the Map of users
    for user in userList:
        print user
        try:
            #query reddit for the JSON
            r = requests.get('http://www.reddit.com/user/'+user+'/submitted.json',params=params)
            json = r.json()
            data = json.get('data')
            #make sure the json contained data
            if isinstance(data,types.NoneType):
                continue
            chillun = data.get('children')
            #sanity check - should have one child if the user still has posts
            #added user may not have posts if they were deleted
            if len(chillun) == 1:
                print 'has chillun'
                child = chillun[0]
                data = child.get('data')
                postTime = data.get('created_utc')
                print 'post created at',postTime
                print 'last seen at',userList[user]
                #if the time of the posting is greater than the last UTC seen, this post is newer
                if postTime > userList[user]:
                    #send notification to Snarl
                    showNotification(user,'http://www.reddit.com/user/'+user+'/submitted')
                    #used in debug
                    didPost = True
                #update this user's last seen UTC
                userList[user] = postTime
        except:
            print 'handled error'
        # reddit API says to limit requests to 30/minute
        sleep(3)

    #re-pickle the Map so it can be used next time
    f = open(pickleFile,'wb')
    pickle.dump(userList,f)
    f.close()

    # DEBUG 
    #if not didPost:
    #    showNotification('No Posts','No new posts at this time')
    # /DEBUG
    
if __name__ == '__main__':
    main()

